
/******************************************************************************
*@file  : main.c
*@brief : main program
******************************************************************************/

#include "main.h" 
#include "app.h"   

uint8_t SPI_Protect_4KB(uint16_t *out_data);  
uint8_t SPI_UNProtect(uint16_t *out_data);  
uint16_t SPI_Read_Status_Register(void); 
uint8_t HAL_NORFLASH_ProgramPage(uint32_t addr, uint8_t *buff, uint32_t len);

uint32_t table1_test[25];  

/******************************************************************************
*@brief : main program
*@param : none
*@return: none
******************************************************************************/
int main(void)
{
    uint16_t spi_status, i;  
    uint8_t  result;   
    
	HAL_Init();  
    SystemClock_Config(SYSCLK_180M_SRC_RC64M, RCC_PCLK1_DIV_1, RCC_PCLK2_DIV_1);   
    HAL_Init_Ex();   
    
    BSP_UART_Init(UART1);  
	
	get_reset_source();
    BSP_MCO_Init(RCC_MCO_HCLK, 10);
    
	printfS("HCK: %u\r\n", HAL_RCC_GetHCLKFreq());
	printfS("PCLK1: %u\r\n", HAL_RCC_GetPCLK1Freq());
	printfS("PCLK2: %u\r\n", HAL_RCC_GetPCLK2Freq());
    printfS("Test Starts:\r\n");  
    
    spi_status = SPI_Read_Status_Register(); 
    printfS("spi status:0x%x\n", spi_status);  //  spi_status != 0x264, it means no Erase/Program Portected  
           
	result = 0;
       
    for (i = 0; i < 25; i++)
    {
       table1_test[i] =  *(uint32_t *)(0x08000000 + i * 4); 
    }
       
    printfS("0x08000000-Value111:0x%x\n", table1_test[0] );  // check 4KB data at the beginning of SPI Flash  
    
    /*Check unprotected aera erase/protect status. For example, 0x08010000 address */
    printfS("0x08010000-Value111:0x%x\n", *(uint32_t *)0x08010000 );  // offset 64KB 
    HAL_NORFLASH_EraseSector(0x08010000);  
    printfS("0x08010000-Value222:0x%x\n", *(uint32_t *)0x08010000 );  
    HAL_NORFLASH_ProgramPage(0x08010000, (uint8_t *)table1_test, 100);  
    printfS("0x08010000-Value333:0x%x\n", *(uint32_t *)0x08010000 );  
    HAL_NORFLASH_EraseSector(0x08010000);   
    
    spi_status = 0;    
    if (0 == result)  
    {
        HAL_NORFLASH_EraseSector(0x08000000);  // if Locked, it should not be erased 
    }
    printfS("0x08000000-Value222:0x%x\n", *(uint32_t *)0x08000000);      
    
    spi_status = 0; 
    result = SPI_UNProtect(&spi_status); // UnProtect the beginning 4KB     
    printfS("111Result:%d. Status Register:0x%x\n", result, spi_status);   
    
    HAL_NORFLASH_EraseSector(0x08000000);   
    printfS("0x08000000-Value333:0x%x\n", *(uint32_t *)0x08000000); 

    HAL_NORFLASH_ProgramPage(0x08000000, (uint8_t *)table1_test, 100); // Write back data to the beginning 4KB  
    
    printfS("0x08000000-Value444:0x%x\n", *(uint32_t *)0x08000000);   
    
    result = SPI_Protect_4KB(&spi_status);  // Lock the beginning 4KB 
    
    printfS("222Result:%d. Status Register:0x%x\n", result, spi_status);   
    
    while(1)
    {
    
    }
}














